package com.itcast.demo02.test;

import com.itcast.demo02.bean.A;
import com.itcast.demo02.bean.Student;
import com.itcast.demo02.bean.User;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @标题 IocFirst
 * @作者 Mr.chen
 * @创建日期 2019/10/9 15:31
 * @版本号 1.0
 **/
public class IocDemo02 {
    /**
     * 默认 Spring允许单例bean 在属性注入时的循环依赖
     */
    @Test
    public void test01(){
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:demo02/ApplicationContext- circle.xml");
        // 设置是否允许循环依赖
        context.setAllowCircularReferences(false);
        context.refresh();
        A a = (A)context.getBean("a");
        System.out.println(a);
        context.close();
    }

    /**
     * 默认 Spring允许 bean覆盖
     */
    @Test
    public void test02(){
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("demo02/ApplicationContext-01.xml", "demo02/ApplicationContext-02.xml");
        // 设置是否允许Bean覆盖
        context.setAllowBeanDefinitionOverriding(false);
        context.refresh();
        User user = (User) context.getBean("user");
        System.out.println(user);
        context.close();
    }
    /**
     * 测试 Bean的完整生命周期
     */
    @Test
    public void test03(){
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("demo02/ApplicationContext-life.xml");
        context.start();
        Student student = (Student) context.getBean("student");
        student.run();
        context.close();
    }

    /**
     * bean的几种创建方式
     */
    @Test
    public void test04(){
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("demo02/ApplicationContext-createBean.xml");
        // 设置是否允许Bean覆盖
        context.start();
        User u1 =  context.getBean("user1",User.class);
        System.out.println(u1);
        User u2 =  context.getBean("user2",User.class);
        System.out.println(u2);
        User u3 =  context.getBean("user3",User.class);
        System.out.println(u3);
        context.close();
    }
}
